package com.xiyuan.smartutils.logging.appender;

import com.xiyuan.smartutils.logging.Level;
import com.xiyuan.smartutils.logging.LogRecord;
import com.xiyuan.smartutils.logging.LoggerManager;

import java.io.PrintStream;

/**
 * the description for class ConsoleHandler
 *
 * @author xiyuan-lgz 2022-10-19 @version v1.0.0 新建与整理
 */
public class ConsoleAppender extends FileAppender {
    public ConsoleAppender() {
        this.getConfig().setConsole(true).setFileName("console.out");
    }
    
    @Override
    public void append(LogRecord record) {
        if (!config.isConsole()) {
            return;
        }
        
        if (!config.isEnableLevel(record.getLevel())) {
            return;
        }
        
        // 输出到文件
        super.append(record);
        
        // 输出到控制台
        this.print(record);
    }
    
    private void print(LogRecord record) {
        try {
            PrintStream printer = System.out;
            if (record.getLevel() == Level.ERROR) {
                printer = System.err;
            }
            print(record, printer);
        }
        catch (Throwable e) {
            LoggerManager.reportError(e);
        }
    }
}
